package com.qdxwx.payment.alipay;

import com.qdxwx.common.utils.TKConvert;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author ZhiYong
 * @updateTime 2021/12/21
 * @description
 */
public class AliPayUtils {

    public static String getContent(Map<String, String> params, String privateKey) {
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        StringBuilder preStr = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            preStr.append(key).append("=").append(value);
            if (i != keys.size() - 1) {
                preStr.append("&");
            }
        }
        return preStr.append(privateKey).toString();
    }


    /**
     * 验证加密签名
     *
     * @param params
     * @param privateKey
     * @return
     */
    public static String sign(Map<String, Object> params, String privateKey) {
        if (privateKey == null) {
            return null;
        }
        List<String> paramList = new ArrayList<>();
        for (String name : params.keySet()) {
            if (name != null && !name.equalsIgnoreCase("sign") && !name.equalsIgnoreCase("sign_type")) {
                paramList.add(name + "=" + params.get(name));
            }
        }
        Collections.sort(paramList);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < paramList.size(); ++i) {
            if (i > 0) {
                content.append("&");
            }
            content.append(paramList.get(i));
        }
        content.append(privateKey);
        return TKConvert.toMD5(content.toString());
    }

    public static String sign(String content, String privateKey) {
        if (privateKey == null) {
            return null;
        } else {
            String signBefore = content + privateKey;
            return TKConvert.toMD5(signBefore);
        }
    }

    public static String check(String urlvalue) {
        try {
            URL e = new URL(urlvalue);
            HttpURLConnection urlConnection = (HttpURLConnection) e.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            return in.readLine();
        } catch (Exception var5) {
            var5.printStackTrace();
            return "";
        }
    }
}
